<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="(header_list as any)"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div class="c_666 fw flex">
          <div
            class="top_item"
            @click="to_project_list(1)"
            @mouseenter="svg_color_list[0] = '#3580eb'"
            @mouseleave="svg_color_list[0] = '#666'"
          >
            <svgBtn
              icon="to"
              style="font-size: 12px !important; transform: rotate(180deg)"
              class="flex_cc m_right5"
              :color="svg_color_list[0]"
            ></svgBtn>
            项目列表
          </div>
          <div class="line"></div>
          <div
            class="top_item"
            @click="to_project_list(2)"
            @mouseenter="svg_color_list[1] = '#3580eb'"
            @mouseleave="svg_color_list[1] = '#666'"
          >
            <svgBtn
              icon="to"
              style="font-size: 12px !important; transform: rotate(180deg)"
              class="flex_cc m_right5"
              :color="svg_color_list[1]"
            ></svgBtn>
            工程列表
          </div>
          <div class="line"></div>
          <div
            class="top_item"
            @click="to_project_list(3)"
            @mouseenter="svg_color_list[2] = '#3580eb'"
            @mouseleave="svg_color_list[2] = '#666'"
          >
            <svgBtn
              icon="to"
              style="font-size: 12px !important; transform: rotate(180deg)"
              class="flex_cc m_right5"
              :color="svg_color_list[2]"
            ></svgBtn>
            工序列表
          </div>
          <div class="line"></div>
          <div>设备列表</div>
        </div>
        <div class="flex">
          <el-button type="primary" @click="show_box = true">新增</el-button>
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        v-loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height:
            height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="名称"
          prop="name"
          key="名称"
          v-if="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          label="代号"
          prop="code"
          key="代号"
          v-if="header_list[1].showTable"
        ></el-table-column>
        <el-table-column label="坐标" key="坐标" v-if="header_list[2].showTable"
          ><template #default="scope: any"
            ><div class="flex_cc">
              <div>
                X:<span style="color: #3580eb">{{ scope.row.xAxis }}</span>
              </div>
              <div class="m_left10 m_right10">
                Y:<span style="color: #3580eb">{{ scope.row.yAxis }}</span>
              </div>
              <div class="">
                Z:<span style="color: #3580eb">{{ scope.row.zAxis }}</span>
              </div>
            </div></template
          ></el-table-column
        >
        <el-table-column label="状态" key="状态" v-if="header_list[2].showTable"
          ><template #default="scope: any">
            <div v-if="scope.row.isDelete">回收站</div>
            <div v-else style="color: #3580eb">进行中</div></template
          ></el-table-column
        >
        <el-table-column label="操作">
          <template #default="scope: any">
            <el-button @click="edit_list(scope)">编辑</el-button>
            <el-button v-if="!scope.row.isDelete" @click="delete_list(scope)"
              >删除</el-button
            >
            <el-button v-else @click="delete_list(scope)">还原</el-button>
            <el-button type="primary" @click="to_metadata(scope)"
              >元数据配置</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0 pagination"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list_debounce()"
        @current-change="list_debounce()"
      />
    </div>
  </div>
  <el-drawer
    v-model="show_box"
    direction="rtl"
    size="60%"
    destroy-on-close
    @close="resetForm(addEngineerform)"
    :close-on-click-modal="false"
  >
    <template #title>
      <h4 v-if="add_form_data.id == ''">新增设备</h4>
      <h4 v-else>编辑设备</h4>
    </template>
    <template #default>
      <el-form
        :model="add_form_data"
        ref="addEngineerform"
        :rules="engineer_rules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="add_form_data.name"
            placeholder="请输入"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="代号" prop="code">
          <el-input
            v-model="add_form_data.code"
            placeholder="请输入"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="坐标">
          <div class="flex">
            X：<el-input
              style="width: 150px"
              class="m_right10"
              type="number"
              v-model="add_form_data.xAxis"
              placeholder="请输入"
            ></el-input
            >Y：<el-input
              style="width: 150px"
              class="m_right10"
              type="number"
              v-model="add_form_data.yAxis"
              placeholder="请输入"
            ></el-input
            >Z：<el-input
              style="width: 150px"
              class="m_right10"
              type="number"
              v-model="add_form_data.zAxis"
              placeholder="请输入"
            ></el-input>
          </div>
        </el-form-item>
        <div class="m_top10 tr">
          <el-button @click="resetForm(addEngineerform)">取消</el-button>
          <el-button
            type="primary"
            :loading="btn_loading"
            @click="submit_engineer(addEngineerform)"
            >确定</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
  <el-drawer
    v-model="metadata_box"
    direction="rtl"
    size="80%"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <template #title><h4>元数据配置表</h4></template>
    <template #default>
      <el-button type="primary" @click="setup_metadata_list">配置</el-button>
      <el-table
        style="text-align: center; margin-top: 10px"
        :data="metadata_list"
        max-height="800"
        border
        v-loading="loading"
        :default-sort="{ prop: 'sort' }"
        :row-style="{
          height:
            height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          label="名称"
          prop="metadataName"
          sortable
        ></el-table-column>
        <el-table-column
          label="编号"
          prop="metadataCode"
          sortable
        ></el-table-column>
        <el-table-column label="类型" sortable prop="type">
          <template #default="scope: any">
            <div v-if="scope.row.type == 1">文本</div>
            <div v-if="scope.row.type == 2">数字</div>
            <div v-if="scope.row.type == 6">判断</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope: any">
            <!-- <el-button @click="edit_metadata_list(scope)">编辑</el-button> -->
            <el-button @click="delete_metadata_list(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </el-drawer>
  <el-drawer
    v-model="set_metadata_box"
    direction="rtl"
    size="50%"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <template #title> <h4>配置</h4></template>
    <template #default>
      <div>
        <el-select
          multiple
          filterable
          style="width: 100%"
          v-model="selected_metadata_list"
        >
          <el-option
            v-for="item in select_metadata_list"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          >
          </el-option>
        </el-select>
      </div>

      <el-button
        class="m_top10"
        type="primary"
        :loading="btn_loading"
        @click="submit_metadata()"
        >保存</el-button
      >
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { check_role, debounce } from '@/utils/check_role' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, nextTick, computed } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import svgBtn from '@/components/svg_button.vue'
import { FormInstance, ElMessage, ElMessageBox } from 'element-plus'
// type FormInstance = InstanceType<typeof ElForm>
const addEngineerform = ref<FormInstance>()
const engineer_rules = ref({
  // 表单验证规则
  name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入设备代号', trigger: 'blur' }],
})
const svg_color_list = ref(['#666', '#666', '#666'])
const list = ref()
const total = ref()
const max_height = ref()
nextTick(() => {
  max_height.value = window.innerHeight - 320 // 带分页的 table 高度
})
const loading = ref(false)
const show_box = ref(false)
const height_size = ref(1)
const header_list = ref([
  {
    label: '名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '代号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      {
        value: '0',
        label: '进行中',
      },
      {
        value: '1',
        label: '回收站',
      },
    ],
  },
])
const props = defineProps({
  projectId: {
    type: String,
  },
  engineeringId: {
    type: String,
  },
  processId: {
    type: String,
  },
})
const page_data = ref({
  current: 1,
  pageSize: 10,
  name: '',
  code: '',
  isDelete: '',
  projectId: computed(() => {
    return props.projectId
  }),
  engineeringId: computed(() => {
    return props.engineeringId
  }),
  processId: computed(() => {
    return props.processId
  }),
})
const add_form_data = ref({
  id: '',
  name: '',
  code: '',
  xAxis: '',
  yAxis: '',
  zAxis: '',
  projectId: computed(() => {
    return props.projectId
  }),
  processId: computed(() => {
    return props.processId
  }),
  engineeringId: computed(() => {
    return props.engineeringId
  }),
})
onMounted(() => {
  console.log(123)
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('刷新成功！')
  })
  setTimeout(() => {
    get_list()
    get_select_metadata_list()
  }, 100)
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const to_project_list = (e) => {
  EventBus.emit('list_change', e)
}
const submit_metadata = () => {
  if (btn_loading.value) return
  btn_loading.value = true
  console.log(selected_metadata_list.value)
  axios
    .request({
      url: serviceApi.szls_device_metadata_crud,
      method: 'post',
      data: {
        deviceId: deviceId.value,
        metadataIdList: selected_metadata_list.value,
      },
    })
    .then((res) => {
      console.log(res)
      ElMessage.success('操作成功！')
      btn_loading.value = false
      set_metadata_box.value = false
      get_metadata_list()
    })
    .catch((err) => {
      btn_loading.value = false
      ElMessage.error(err)
    })
}
const delete_metadata_list = (e) => {
  ElMessageBox.confirm('确定删除该元数据在此设备的配置？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    closeOnClickModal: false,
    type: 'error',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.szls_device_metadata_crud + '/delete',
          method: 'delete',
          data: {
            deviceId: deviceId.value,
            metadataId: e.row.id,
          },
        })
        .then(() => {
          ElMessage.success('操作成功！')
          get_metadata_list()
        })
        .catch((err) => {
          ElMessage.error(err)
        })
    })
    .catch(() => {})
}
const setup_metadata_list = () => {
  selected_metadata_list.value = []
  metadata_list.value.forEach((item) => {
    selected_metadata_list.value.push(item.id)
  })
  set_metadata_box.value = true
}
const metadata_list = ref([])
const select_metadata_list = ref([])
const selected_metadata_list = ref([])
const metadata_box = ref()
const set_metadata_box = ref()
const deviceId = ref()
const to_metadata = (e) => {
  deviceId.value = e.row.id
  get_metadata_list()
  metadata_box.value = true
}
const get_metadata_list = () => {
  axios
    .request({
      url: serviceApi.szls_device_metadata_list,
      method: 'post',
      data: {
        deviceId: deviceId.value,
      },
    })
    .then((res) => {
      console.log(res)
      metadata_list.value = res.data
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const select_metadata_paege_data = ref({
  current: 1,
  pageSize: 10000,
  projectId: props.projectId,
  engineeringId: props.engineeringId,
  name: '',
})
const get_select_metadata_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.szls_engineeringMetadata_list,
      method: 'post',
      data: select_metadata_paege_data.value,
    })
    .then((res) => {
      console.log(res)
      loading.value = false
      res.data.content.forEach((item) => {
        item.sort = parseInt(item.sort)
      })
      select_metadata_list.value = res.data.content.filter(
        (item) => item.status == true
      )
    })
    .catch((err) => {
      loading.value = false
      ElMessage.error(err)
    })
}
const submit_engineer = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      axios
        .request({
          url:
            add_form_data.value.id == ''
              ? serviceApi.szls_device_crud
              : serviceApi.szls_device_crud + '/' + add_form_data.value.id,
          method: add_form_data.value.id == '' ? 'post' : 'put',
          data: add_form_data.value,
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            btn_loading.value = false
            resetForm(formEl)
            get_list()
            show_box.value = false
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
          btn_loading.value = false
        })
    }
  })
}
const delete_list = (e) => {
  ElMessageBox.confirm(
    e.row.isDelete ? '确定还原：' + e.row.name : '确定删除：' + e.row.name,
    '',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      type: 'error',
    }
  )
    .then(() => {
      axios
        .request({
          url: !e.row.isDelete
            ? serviceApi.szls_device_crud + '/' + e.row.id
            : serviceApi.szls_device_restore + '/' + e.row.id,
          method: !e.row.isDelete ? 'delete' : 'put',
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
          }, 1000)
        })
        .catch((err) => {
          console.log(err)
          ElMessage.error(err)
        })
    })
    .catch(() => {})
}
const edit_list = (e) => {
  add_form_data.value = {
    projectId: add_form_data.value.projectId,
    processId: add_form_data.value.processId,
    id: e.row.id,
    name: e.row.name,
    code: e.row.code,
    xAxis: e.row.xAxis,
    yAxis: e.row.yAxis,
    zAxis: e.row.zAxis,
    engineeringId: add_form_data.value.engineeringId,
  }
  show_box.value = true
}
const btn_loading = ref(false)
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.szls_device_list,
      method: 'post',
      data: page_data.value,
    })
    .then((res) => {
      console.log(res)
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}
let list_debounce = debounce(200, get_list)
const search_key = () => {
  page_data.value.name = header_list.value[0].value
  page_data.value.code = header_list.value[1].value
  page_data.value.isDelete =
    header_list.value[2].value == ''
      ? ''
      : header_list.value[2].value == '1'
      ? (true as any)
      : (false as any)
  get_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  console.log(123)
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    name: '',
    projectId: add_form_data.value.projectId,
    code: '',
    xAxis: '',
    yAxis: '',
    zAxis: '',
    engineeringId: add_form_data.value.engineeringId,
    processId: add_form_data.value.processId,
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped>
.top_item {
  border: 1px solid #ccc;
  cursor: pointer;
  padding: 5px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  &:hover {
    color: #3580eb;
    border-color: #3580eb;
  }
}
.line {
  background-color: #333;
  width: 1px;
  height: 16px;
  margin: 0 10px;
}
</style>
